from project.models import ProjectDocument, Project
from pms.common.utils import flatten_view


def document_view(document):
    assert isinstance(document, ProjectDocument)
    return {
        'id': document.id,
        'name': document.name,
        'href': document.href,
        'pid': document.pid.id
    }


def project_add_document(project, name, href):
    assert isinstance(project, Project)
    new_document = ProjectDocument(name=name, href=href, pid=project)
    new_document.save()
    return new_document


def update_document(document, view):
    assert isinstance(document, ProjectDocument)
    argv = flatten_view(view, {
        'name': 'name',
        'href': 'href'
    })
    document.__dict__.update(**argv)
    document.save()
    return document
